package com.lottery.game.websocket.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.lottery.game.core.modules.entity.user.ChatRecord;
import com.lottery.game.core.modules.entity.user.GameUser;
import com.lottery.game.core.modules.service.app.ChatRecordService;
import com.lottery.game.core.modules.service.app.GameUserService;
import com.lottery.game.core.modules.service.app.OnlineAppContext;
import com.lottery.game.core.modules.service.app.WebSocketService;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;

import lombok.extern.slf4j.Slf4j;

import static com.lottery.game.common.constants.GameConstants.CHATTYPE_CUSREPLY;
import static com.lottery.game.common.constants.GameConstants.CHATTYPE_GROUPCHAT;
import static com.lottery.game.common.constants.GameConstants.CHATTYPE_SYSTEM_MSG;
import static com.lottery.game.common.constants.GameConstants.CHAT_ID;
import static com.lottery.game.common.constants.GameConstants.CHAT_TYPE;
import static com.lottery.game.common.constants.GameConstants.USER_ID;

@Slf4j
public class OutboundChannelInterceptorAdapter implements ChannelInterceptor {

	private GameUserService gameUserService;
	private WebSocketService webSocketService;
	private ChatRecordService chatRecordService;
	private OnlineAppContext onlineAppContext;

	public OutboundChannelInterceptorAdapter(GameUserService gameUserService, WebSocketService webSocketService,
			ChatRecordService chatRecordService, OnlineAppContext onlineAppContext) {
		this.gameUserService = gameUserService;
		this.webSocketService = webSocketService;
		this.chatRecordService = chatRecordService;
	}

	@Override
	public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
//		log.info("   ---OutboundChannelInterceptorAdapter.afterSendCompletion---   ");
		ChannelInterceptor.super.afterSendCompletion(message, channel, sent, ex);
	}

	@Override
	public void afterReceiveCompletion(Message<?> message, MessageChannel channel, Exception ex) {
//		log.info("   ---OutboundChannelInterceptorAdapter.afterReceiveCompletion---   ");
		ChannelInterceptor.super.afterReceiveCompletion(message, channel, ex);
	}

	@Override
	public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
//		log.info("   ---OutboundChannelInterceptorAdapter.postSend---   ");

		StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);//消息头访问器
		StompCommand command = accessor.getCommand();
		Boolean isHeartBeat = accessor.isHeartbeat();
		if(isHeartBeat) {
			// sent heart beat message
			return;
		}

		if (command == null) {
			return ;// 避免非stomp消息类型，例如心跳检测
		}

//		String token = "demo-outbound-token";
//		log.info("---OutboundChannelInterceptorAdapter.SocketChannelIntecepter -> token = {}", token);
		log.info("---command:  {}", accessor.getCommand());

		switch (command) {
		case CONNECT:
//			connect(token);
			break;
		case DISCONNECT:
//			disconnect(token);
			break;
		case SUBSCRIBE:

			break;

		case UNSUBSCRIBE:

			break;
		case SEND:
			send(accessor, channel, message.getPayload());
			break;
		default:
			break;
		}
	}

	private void send(StompHeaderAccessor accessor, MessageChannel channel, Object payload) {
		String chatId = (String) accessor.getSessionAttributes().get(CHAT_ID);
		String chatType = (String) accessor.getSessionAttributes().get(CHAT_TYPE);
		String userId = (String) accessor.getSessionAttributes().get(USER_ID);

		// 构建消息数据
		ChatRecord chatRecord = new ChatRecord();
		UUID uuid = UUID.randomUUID();
		chatRecord.setId(uuid.toString());
		chatRecord.setChatType(chatType);
		chatRecord.setSenderUserid(userId);
		chatRecord.setMsgContent((String) payload);
        chatRecord.setMessageStatus("0");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		chatRecord.setTimestamp(sdf.format(new Date()));


		//用户禁言状态，默认否
		boolean userBanned = false;
		GameUser user = null;


		log.info("---客服聊天---chatType：{}", chatType);
		switch (chatType) {
		case CHATTYPE_GROUPCHAT: // 房间群聊
			chatRecord.setRoomnumber(chatId);
			user = gameUserService.get(userId);
			if (user != null) {
			    chatRecord.setSenderPhone(user.getPhone());
                chatRecord.setSendernickname(user.getUsername());
                chatRecord.setSenderphoto(user.getPhotourl());

			} else {
				chatRecord.setSenderPhone("null");
				chatRecord.setSendernickname(userId);
			}
			break;
//		case CHATTYPE_CUSSERVICECHAT: // 客服聊天
//			log.info("---客服聊天---");
//			chatRecord.setSenderUserid(userId);
//			user = gameUserService.get(userId);
//			if (user != null) {
//				// 判断用户的禁言状态
//				chatRecord.setSenderPhone(user.getPhone());
//				chatRecord.setSendernickname(user.getUsername());
//				chatRecord.setSenderphoto(user.getPhotourl());
//			} else {
//				chatRecord.setSenderPhone("null");
//				chatRecord.setSendernickname(userId);
//			}
//			//用户前端发放消息给客服时,推送一条通知给后端服务器
//
//			Map<String, String> map = new HashMap<>(1);
//			map.put("sendUserId", userId);
//			String sendMsg = JSONObject.toJSONString(map);
//			webSocketService.sendToEveryChatUser(sendMsg, SYS_MSG_CUSSERVICECHAT_NOTICE);
//
//			break;
		case CHATTYPE_CUSREPLY: // 客服回复
		    chatRecord.setSenderPhone("null");
            chatRecord.setSendernickname(userId);
            chatRecord.setReceiverUserid(chatId);
			break;
		case CHATTYPE_SYSTEM_MSG: // 系统WS连接，默认不允许用户推送消息到后台，防止插入数据库影响数据
			userBanned = true;
			break;
		default:
			break;
		}

		String sendMsg = JSONObject.toJSONString(chatRecord);

		// 有chatId且没有被禁掉
		if (!StringUtils.isEmpty(chatId) && !userBanned) {
			Set<String> userIdList = onlineAppContext.getUserIds(chatId);

			// WS 发给chatId下的每一个User
			if(!CollectionUtils.isEmpty(userIdList)) {
				userIdList.forEach(uId -> {
					webSocketService.sendToTheUser(sendMsg, uId, chatId,null);
					chatRecord.setMessageStatus("1");
				});
			}

			String orginMsg = "";
			try {
				JSONObject obj = JSONObject.parseObject(chatRecord.getMsgContent());
				orginMsg = obj.getString("message");
				chatRecord.setOrginMsg(orginMsg);
				Boolean  isBetsSend = obj.getBoolean("betsSend");
				if(isBetsSend!=null) {
					if (isBetsSend) {
						chatRecord.setGameroomId("betsSend");
					}
				}
			}catch(Exception e) {
				e.printStackTrace();
			}
			// 存入数据库
			chatRecordService.addChatRecord(chatRecord);
		}

	}

	//连接成功
	private void connect(String token){
		log.info("   ---OutboundChannelInterceptorAdapter.connect---token:{}   ", token);

	}


	//断开连接
	private void disconnect(String token){
		log.info("   ---OutboundChannelInterceptorAdapter.disconnect---token:{}   ", token);
		//用户下线操作
		//UserChatController.onlineUser.remove(sessionId);
	}

}
